package de.grosjohann.android.feuerwehr;

import java.util.List;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceActivity;
import android.util.Log;
import de.grosjohann.android.ColorPickerDialog;
import de.grosjohann.android.ColorPickerDialog.OnColorChangedListener;
import de.grosjohann.android.feuerwehr.c2dm.C2DM;
import de.grosjohann.android.feuerwehr.service.FMSNotificationService;
import de.grosjohann.android.feuerwehr.service.IntentServiceFacade;
import de.grosjohann.android.feuerwehr.service.WeatherNotificationService;
import de.grosjohann.android.feuerwehr.service.WidgetUpdateService;
import de.grosjohann.android.feuerwehr.type.FMSStatusType;
import de.grosjohann.android.feuerwehr.type.FireIndexType;
import de.grosjohann.android.feuerwehr.type.WeatherWarningType;
import de.grosjohann.android.feuerwehr.util.PrefsUtil;

public class PrefsActivity
  extends PreferenceActivity
  implements OnSharedPreferenceChangeListener, OnPreferenceClickListener {

  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.layout.prefs);
  }

  @Override
  protected void onResume() {
    super.onResume();

    // Set up a listener whenever a key changes            
    getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);

    getPreferenceScreen().getPreferenceManager().findPreference(getString(R.string.prefKeyFMSNotifications))
        .setOnPreferenceClickListener(this);
    getPreferenceScreen().getPreferenceManager().findPreference(getString(R.string.prefKeyWeatherNotifications))
        .setOnPreferenceClickListener(this);
    getPreferenceScreen().getPreferenceManager().findPreference(getString(R.string.prefKeyFireIndexNotifications))
        .setOnPreferenceClickListener(this);

    getPreferenceScreen().getPreferenceManager().findPreference(getString(R.string.prefKeyWidgetFontColor))
        .setOnPreferenceClickListener(this);

    enablePushSync();
    setNotificationSettings();
  }

  @Override
  protected void onPause() {
    super.onPause();

    // Unregister the listener whenever a key changes            
    getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
  }

  @Override
  public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
    final Context ctx = getApplicationContext();
    final String prefKeyInterval = getString(R.string.prefKeyInterval);
    final String prefKeyNotification = getString(R.string.prefKeyNotification);
    final String prefKeyPush = getString(R.string.prefKeyPush);

    if (prefKeyInterval.endsWith(key)) {
      IntentServiceFacade.restartRepeating(ctx, FMSNotificationService.class);
      IntentServiceFacade.restartRepeating(ctx, WeatherNotificationService.class);

    } else if (prefKeyNotification.endsWith(key)) {
      setNotificationSettings();

    } else if (prefKeyPush.endsWith(key)) {
      setPushSync();
    }
  }

  private void setNotificationSettings() {
    final Context ctx = getApplicationContext();

    /*
     * Einstellung fuer Vibration enablen/disabeln
     */
    Preference prefVibration =
        getPreferenceScreen().getPreferenceManager().findPreference(getString(R.string.prefKeyVibration));
    prefVibration.setEnabled(PrefsUtil.getBoolean(ctx, R.string.prefKeyNotification, false));

    /*
     * Einstellung fuer Ringtone enablen/disabeln
     */
    Preference prefRingtone =
        getPreferenceScreen().getPreferenceManager().findPreference(getString(R.string.prefKeyRingtone));
    prefRingtone.setEnabled(PrefsUtil.getBoolean(ctx, R.string.prefKeyNotification, false));
  }

  private void enablePushSync() {

    Preference prefPushSync =
        getPreferenceScreen().getPreferenceManager().findPreference(getString(R.string.prefKeyPush));
    prefPushSync.setEnabled(isGoogleMarketInstalled() && isGoogleAccountActive());
  }

  private boolean isGoogleAccountActive() {
    AccountManager am = (AccountManager) getSystemService(ACCOUNT_SERVICE);
    Account[] account = am.getAccountsByType("com.google");
    return (account.length > 0);
  }

  private boolean isGoogleMarketInstalled() {
    PackageManager pm = getPackageManager();
    Intent market = new Intent(Intent.ACTION_VIEW, Uri.parse("market://search?q=dummy"));
    List<ResolveInfo> list = pm.queryIntentActivities(market, 0);

    return (list != null) && (list.size() > 0);
  }

  private void setPushSync() {
    final Context ctx = getApplicationContext();

    if (PrefsUtil.getBoolean(ctx, R.string.prefKeyPush, false)) {
      C2DM.register(ctx);
    } else {
      C2DM.unregister(ctx);
    }
  }

  @Override
  public boolean onPreferenceClick(Preference preference) {
    final Context ctx = getApplicationContext();

    if (preference.getKey().equals(getString(R.string.prefKeyFMSNotifications))) {
      Intent i = new Intent(this, NotifyPrefsActivity.class);
      i.putExtra(NotifyPrefsActivity.SPEC_NOTIFY, FMSStatusType.EINSATZBEREIT_GH);
      startActivity(i);
      return true;
    } else if (preference.getKey().equals(getString(R.string.prefKeyWeatherNotifications))) {
      Intent i = new Intent(this, NotifyPrefsActivity.class);
      i.putExtra(NotifyPrefsActivity.SPEC_NOTIFY, WeatherWarningType.KEINE_WARNUNGEN);
      startActivity(i);
      return true;
    } else if (preference.getKey().equals(getString(R.string.prefKeyFireIndexNotifications))) {
      Intent i = new Intent(this, NotifyPrefsActivity.class);
      i.putExtra(NotifyPrefsActivity.SPEC_NOTIFY, FireIndexType.SEHR_GERINGE_GEFAHR);
      startActivity(i);
      return true;
    } else if (preference.getKey().equals(getString(R.string.prefKeyWidgetFontColor))) {

      final int defaultColor =
          PrefsUtil.getIntDefault(ctx, R.string.prefKeyWidgetFontColor, Integer.toString(Color.parseColor("#000000")));

      ColorPickerDialog dialog = new ColorPickerDialog(this, new OnColorChangedListener() {

        @Override
        public void colorChanged(int color) {
          Log.i("Prefs", color + "");
          PrefsUtil.setString(ctx, R.string.prefKeyWidgetFontColor, Integer.toString(color));
          IntentServiceFacade.startOnce(ctx, WidgetUpdateService.class);
        }
      }, defaultColor);

      dialog.show();
      return true;
    }
    return false;
  }
}